<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->

    <div
      class="main-wrap"
      ref="mainWrap"
      :style="{ bottom: user ? '88px' : '0' }"
    >
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- 模板中的方法传参直接为$event

            组件传参也需要进行修改:
            c传参 :props， :is_followed="article.is_followed"
            修改;自定义事件 ：  @update-is-followed="article.is_followed = $event"
            可简写成v-model格式:
            v-model相当于默认传参:value="article.is_followed",@input="xxx"

            入股需要修改v-model传参的属性和自定义事件名称，可修改子组件的model属性

          -->
          <follow-user
            v-if="user"
            class="follow-btn"
            :aut_id="article.aut_id"
            v-model="article.is_followed"
          />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="contentRef"
        ></div>
        <van-divider>正文结束</van-divider>

        <!-- 文章评论 -->
        <article-comments
          ref="commentPoi"
          @onload-success="commCount = $event"
          :source="articleId"
          :commentList="commentList"
          @replayClick="replayClickFn"
        />

        <!-- 底部区域 -->
        <div class="article-bottom" v-if="user">
          <van-button
            class="comment-btn"
            type="default"
            round
            size="small"
            @click="isPostShow = true"
            >写评论</van-button
          >

          <van-icon
            name="comment-o"
            :badge="commCount > 999 ? '999+' : commCount"
            color="#777"
            @click="scrollToCommFn"
          />
          <!-- <van-icon color="#777" name="good-job-o" /> -->
          <good-job v-model="article.attitude" :articleId="article.art_id" />

          <!-- <van-icon color="#777" name="star-o" /> -->
          <collect-article
            v-model="article.is_collected"
            :articleId="article.art_id"
          />
          <van-icon
            name="share"
            color="#777777"
            @click="isShowShare = true"
          ></van-icon>
        </div>
        <!-- /底部区域 -->

        <!-- 添加评论 -->
        <van-popup position="bottom" v-model="isPostShow">
          <post-comment @add-comment="addCommentFn" :target="articleId" />
        </van-popup>
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errorStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadArtcileInfo"
          >点击重试</van-button
        >
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->

      <back-to-top :refname="'mainWrap'" v-if="isShowTopIcon" :offsetLeft="0" />
      <!-- 评论回复弹框 -->
      <!-- van-popup:只在第一次显示时会加载视图请求数据，后面再显示时不会再次加载数据， -->
      <van-popup
        position="bottom"
        v-model="isReplayshow"
        closeable
        round
        :style="{ height: '90%' }"
      >
        <!-- 利用v-if来进行组件数据的加载和销毁 -->
        <comment-replay
          v-if="isReplayshow"
          :comment="comment"
          :articleId="articleId"
          @click-close="isReplayshow = false"
        />
      </van-popup>

      <!-- 分享组件弹框 -->
      <van-share-sheet
        v-model="isShowShare"
        title="立即分享给好友"
        description="本功能为组件测试功能"
        :options="options"
        @select="onSelect"
      />
      <!-- /分享组件弹框 -->
    </div>
  </div>
</template>
<script>
import { getArticleByIdAPI } from '@/api'
import { ImagePreview } from 'vant'
import './markdown.css'
import FollowUser from '@/components/FollowUser.vue'
import CollectArticle from '@/components/Collect.Article.vue'
import GoodJob from '@/components/GoodJob.vue'
import ArticleComments from '@/components/ArticleComments.vue'
import PostComment from '../../components/PostComment.vue'
import CommentReplay from '../../components/CommentReplay.vue'
import { mapState } from 'vuex'
import BackToTop from '../../components/BackToTop.vue'

export default {
  name: 'ArticleIndex',
  components: {
    FollowUser,
    CollectArticle,
    GoodJob,
    ArticleComments,
    PostComment,
    CommentReplay,
    BackToTop
  },
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  },
  data () {
    return {
      article: {},
      loading: true,
      errorStatus: 0,
      isFollowLoading: false,
      commCount: 0, // 评论数量
      isPostShow: false, // 写评论
      commentList: [], // 默认评论列表
      isReplayshow: false, // 回复评论弹框
      comment: {}, // 评论对象
      isShowShare: false, // 是否分享
      options: [
        // 分享弹框配置options
        [
          { name: '微信', icon: 'wechat' },
          { name: '朋友圈', icon: 'wechat-moments' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' }
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' }
        ]
      ],
      isShowTopIcon: false // s是否显示返回顶部的按钮
    }
  },
  created () {
    this.loadArtcileInfo()
  },
  mounted () {
    // console.log(this.$refs) // 有值
    // setTimeout(() => {
    //   console.dir(this.$refs.contentRef)
    // }, 10)
    // console.dir(this.$refs.contentRef) // undefined : ref 定位 在v-if/v-show/v-for 的节点中，ref没有加载

    const _this = this
    // 定义页面滚动监听事件
    this.$refs.mainWrap.onscroll = function (e) {
      e.target.scrollTop > e.target.clientHeight
        ? (_this.isShowTopIcon = true)
        : (_this.isShowTopIcon = false)
    }
  },
  methods: {
    async loadArtcileInfo () {
      this.loading = true
      try {
        const { data: res } = await getArticleByIdAPI(this.articleId)
        // console.log(res)
        this.article = res.data
        this.loading = false

        // nextTick 函数是在数据改变后引发视图更新完成才执行，此处不能用nextTick函数
        // this.$nextTick(() => {
        //   this.previewImg()
        // })
        // 在created方法中调用，页面dom还没有加载出来，获取不到dom节点，
        // 使用计时器函数可以获取
        // 箭头函数中的this 为外部的this，如果使用匿名函数，this就不是指外部 的 this了
        setTimeout(() => {
          this.previewImg()
        }, 0)
      } catch (err) {
        this.loading = false
        if (err.response && err.response.status === 404) {
          this.errorStatus = 404
        }
        this.$toast('获取失败')
      }
    },
    // 设置图片预览
    previewImg () {
      const contentEl = this.$refs.contentRef
      // console.log(contentEl)
      const allImg = contentEl.querySelectorAll('img')
      const images = []
      // allImg ：dom 元素数组为一个伪数组，没有map 方法，只能用foreach
      allImg.forEach((element, index) => {
        images.push(element.src)
        element.onclick = () => {
          ImagePreview({
            images,
            startPosition: index
          })
        }
      })
    },
    // 发布新的评论
    addCommentFn (obj) {
      this.isPostShow = false
      obj.is_liking = false
      this.commentList.unshift(obj)
      this.commCount++
    },
    // 新增回复评论
    replayClickFn (comm) {
      this.isReplayshow = true
      // console.log(comm)
      this.comment = comm
    },
    // 设置页面滚到评论列表位置
    scrollToCommFn () {
      if (this.$refs.commentPoi) {
        const top = this.$refs.commentPoi.$el.offsetTop
        // 设置页面滚动到指定位置，需要设置指定元素的父元素滚动到指定元素即可
        this.$refs.mainWrap.scrollTo({
          top: top,
          behavior: 'smooth'
        })
      }
    },
    // 分享面板点击条目
    onSelect (option) {
      this.$toast(option.name)
      this.isShowShare = false
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
